package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.JsonBuilder;
import cn.com.winning.ecare.utils.MessageUtils;
import cn.com.winning.ecare.utils.StringUtil;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.widgets.CustomProgressDialog;

/**
 * 医生排班信息
 * 
 * @author Administrator
 */
public class GhFrive extends Activity
{
	private CustomProgressDialog proDialog;// 加载框
	private GhFrive oThis = this;
	private List<Map<String, Object>> list_ys;
	private List<Map<String, String>> brList = new ArrayList<Map<String, String>>();
	private ListView brListview;
	AlertDialog alert_brlist = null;
	private Intent mIntent;
	private MyAdapter myadapter;
	private ListView lv;
	private String strysgh;
	private String strpbdate;
	private String strghf;
	private String strsyhs;
	private String strKsId;
	private String yydate;
	private String ysgh;
	private String pbmxid;
	private String ghf;
	private String ksname;
	private String ksid;
	private String ysname;
	MyApplication myApplication;
	int screenheight;
	int screenwidth;
	BrListAdapter adapter = null;
	private static final int LOADSUCC = 2;
	private static final int LOADFAIL = 3;
	private String patid = "";
	private String cardno = "";
	private ImageButton bt_preview;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.gh_frive);
		myApplication = (MyApplication) getApplication();
		myApplication.addActivity(this);
		// 获取屏幕分辨率
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		screenheight = dm.heightPixels;
		screenwidth = dm.widthPixels;
		// 获取控件
		findView();

		// 获取数据
		getData();

		// 点击事件
		setOnClick();

	}

	private void setOnClick()
	{
		// 设置preview监听
		// ks_preview.setOnClickListener(new View.OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		//
		// finish();
		//
		// }
		// });

	}

	private void findView()
	{
		list_ys = new ArrayList<Map<String, Object>>();
		mIntent = getIntent();
		if (mIntent != null)
		{
			strysgh = mIntent.getStringExtra("strysgh");
			strKsId = mIntent.getStringExtra("strksid");
		}
		lv = (ListView) this.findViewById(R.id.ghlist_pbsub);

	}

	private void getData()
	{
		proDialog = CustomProgressDialog.createDialog(this);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new Thread(new LoadData()).start();
	}

	class LoadData implements Runnable
	{

		public void run()
		{
			// TODO Auto-generated method stub
			Looper.prepare();
			iniPb();
			Looper.loop();
		}
	}

	private void iniPb()
	{
		try
		{
			Message msg = myHandler.obtainMessage();
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("ysgh", strysgh));
			ls.add(new BasicNameValuePair("ksdm", strKsId));
			JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.GHGETPBLIST, ls);
			List<Map<String, Object>> tempmain = new ArrayList<Map<String, Object>>();
			if (json != null && !json.equals(""))
			{
				if (!json.toString().equals("{\"msg\":\"系统错误！\",\"success\":\"false\"}"))
				{
					if (new JSONArray(json.getString("pbinfo")).length() > 0)
					{
						// 获取收费信息
						JSONArray jsonArr = new JSONArray(json.getString("pbinfo"));
						JSONObject js = null;
						for (int i = 0; i < jsonArr.length(); i++)
						{
							Map<String, Object> map_ys = new HashMap<String, Object>();
							js = jsonArr.getJSONObject(i);
							map_ys.put("ysgh", js.getString("ysgh"));
							map_ys.put("pbdate", js.getString("pbdate"));
							map_ys.put("ghf", js.getString("ghf"));
							map_ys.put("syhs", js.getString("syhs"));
							map_ys.put("pbmxid", js.getString("pbmxid"));
							map_ys.put("ksname", js.getString("ksname"));
							map_ys.put("ksid", js.getString("ksid"));
							map_ys.put("ysname", js.getString("ysname"));
							tempmain.add(map_ys);
						}
						msg.what = 0;
						msg.obj = tempmain;
					}
					else
					{
						msg.what = -1;
						msg.obj = "暂无数据";
					}

				}
				else
				{
					msg.what = -1;
					msg.obj = "系统错误";
				}

			}
			else
			{
				msg.what = -1;
				msg.obj = "网络连接失败!";
			}
			myHandler.sendMessage(msg);
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			// 捕捉异常
			Message msg = myHandler.obtainMessage();
			msg.what = -1;
			msg.obj = e.toString();
			myHandler.sendMessage(msg);
		}
	}

	/**
	 * 主线程状态更新
	 */
	Handler myHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case -1:
					proDialog.dismiss();
					Toast.makeText(oThis, (String) msg.obj, Toast.LENGTH_SHORT).show();
					break;
				case 0:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					if (msg.obj != null)
					{
						list_ys = (List<Map<String, Object>>) msg.obj;
					}
					if (myadapter == null)
					{
						myadapter = new MyAdapter();
					}

					lv.setAdapter(myadapter);
					myadapter.notifyDataSetChanged();
					break;
				case 1:
					proDialog.dismiss();
					// setHosInfo();
					break;
				case LOADSUCC:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					if (msg.obj != null)
					{
						brList = (List<Map<String, String>>) msg.obj;
					}
					if (brList.size() > 0 && !brList.isEmpty())
					{
						initBrListDialog();
					}
					else
					{
						initYyDialog();
					}
					adapter.notifyDataSetChanged();
					break;
				case LOADFAIL:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
//					Toast.makeText(oThis, (String) msg.obj, Toast.LENGTH_SHORT).show();
					initYyDialog();
					break;

				default:
					break;
			}
		};
	};

	private void setys()
	{
		myadapter = new MyAdapter();
		myadapter.notifyDataSetChanged();
		lv.setAdapter(myadapter);

	}

	/**
	 * 自定义listview布局显示内容
	 */
	class MyAdapter extends BaseAdapter
	{

		public int getCount()
		{
			// TODO Auto-generated method stub
			return list_ys.size();
		}

		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return list_ys.get(position);
		}

		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub
			View view = convertView;

			view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.gh_frive_sub, null);

			strpbdate = (CharSequence) list_ys.get(position).get("pbdate") == null ? "" : list_ys.get(position).get("pbdate")
					.toString();
			strysgh = (CharSequence) list_ys.get(position).get("ysgh") == null ? "" : list_ys.get(position).get("ysgh").toString();
			strghf = (CharSequence) list_ys.get(position).get("ghf") == null ? "" : list_ys.get(position).get("ghf").toString();
			strsyhs = (CharSequence) list_ys.get(position).get("syhs") == null ? "" : list_ys.get(position).get("syhs").toString();
			TextView tv_pd = (TextView) view.findViewById(R.id.pb_date);
			tv_pd.setText(strpbdate);
			TextView tv_ghf = (TextView) view.findViewById(R.id.ghf2);
			tv_ghf.setText(strghf);
			TextView tv_syhs = (TextView) view.findViewById(R.id.syhs2);
			tv_syhs.setText(strsyhs);

			Button tv_yy = (Button) view.findViewById(R.id.pb_yy);
			tv_yy.setText("  " + "预约" + "  ");
			yydate = strpbdate;
			ysgh = strysgh;
			pbmxid = (CharSequence) list_ys.get(position).get("pbmxid") == null ? "" : list_ys.get(position).get("pbmxid").toString();
			ghf = strghf;
			ksname = (CharSequence) list_ys.get(position).get("ksname") == null ? "" : list_ys.get(position).get("ksname").toString();
			ksid = (CharSequence) list_ys.get(position).get("ksid") == null ? "" : list_ys.get(position).get("ksid").toString();
			ysname = (CharSequence) list_ys.get(position).get("ysname") == null ? "" : list_ys.get(position).get("ysname").toString();
			tv_yy.setOnClickListener(new View.OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					// TODO Auto-generated method stub

					proDialog = CustomProgressDialog.createDialog(oThis);
					proDialog.setMessage("数据加载中...");
					proDialog.show();
					proDialog.setCanceledOnTouchOutside(false);
					new Thread(new InitBrThread()).start();
					// AlertDialog.Builder builder = new AlertDialog.Builder(oThis);
					// builder.setTitle("提示");
					// builder.setMessage("确定要预约吗?");
					// builder.setPositiveButton("确定", new
					// DialogInterface.OnClickListener()
					// {
					//
					// @Override
					// public void onClick(DialogInterface dialog, int which)
					// {
					// try
					// {
					//
					// Intent intent = new Intent(GhFrive.this, GhSix.class);
					// intent.putExtra("strpbdate", yydate);
					// intent.putExtra("strysgh", ysgh);
					// intent.putExtra("pbmxid", pbmxid);
					// intent.putExtra("ghf", ghf);
					// intent.putExtra("ksname", ksname);
					// intent.putExtra("ksid", ksid);
					// intent.putExtra("ysname", ysname);
					//
					// startActivity(intent);
					// }
					// catch (Exception e)
					// {
					// MessageUtils.showMsgToastBottom(oThis, "保存失败！");
					// }
					// }
					// });
					// builder.setNegativeButton("取消", null);
					// AlertDialog alertDialog = builder.create();
					// alertDialog.show();
				}
			});

			return view;
		}
	}

	/**
	 * 自定义listview布局显示内容
	 * 
	 * @author zjj
	 */
	class BrListAdapter extends BaseAdapter
	{

		public int getCount()
		{

			return brList.size();
		}

		public Object getItem(int position)
		{

			return brList.get(position);
		}

		public long getItemId(int position)
		{

			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{
			ViewHolder holder = null;
			if (convertView == null)
			{
				holder = new ViewHolder();
				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.brlist_item, null);
				holder.brlist_item_hzxm = (TextView) convertView.findViewById(R.id.brlist_item_hzxm);
				holder.brlist_item_cardno = (TextView) convertView.findViewById(R.id.brlist_item_cardno);
				holder.brlist_item_jksj = (TextView) convertView.findViewById(R.id.brlist_item_jksj);
				convertView.setTag(holder);
			}
			else
			{
				holder = (ViewHolder) convertView.getTag();
			}
			holder.brlist_item_hzxm.setText(brList.get(position).get("hzxm"));
			holder.brlist_item_cardno.setText(brList.get(position).get("cardno"));
			holder.brlist_item_jksj.setText(brList.get(position).get("jksj"));
			return convertView;
		}
	}

	static class ViewHolder
	{
		TextView brlist_item_hzxm;
		TextView brlist_item_cardno;
		TextView brlist_item_jksj;
	}

	private class InitBrThread implements Runnable
	{

		@Override
		public void run()
		{
			Looper.prepare();
			initBrList();
			Looper.loop();
		}

	}

	private void initBrList()
	{
		Message message = myHandler.obtainMessage();
		List<NameValuePair> ls = new ArrayList<NameValuePair>();
		ls.add(new BasicNameValuePair("hzxm", myApplication.getHzxm()));
		ls.add(new BasicNameValuePair("sfzh", myApplication.getSfzh()));
		ls.add(new BasicNameValuePair("sjh", myApplication.getSjh()));
		JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.GHFINDBRLIST, ls);
		try
		{
			if (json != null)
			{
				if (json.getBoolean("success"))
				{
					message.obj = JsonBuilder.getInstance().getList(json.getString("msg"));
					message.what = LOADSUCC;
				}
				else
				{
					message.obj = json.getString("msg");
					message.what = LOADFAIL;
				}
			}
			else
			{
				message.obj = "数据获取失败";
				message.what = LOADFAIL;
			}
		}
		catch (Exception e)
		{
			message.obj = "数据获取失败";
			message.what = LOADFAIL;
		}
		myHandler.sendMessage(message);
	}

	private void initBrListDialog()
	{
		LayoutInflater flater = oThis.getLayoutInflater();
		final View view = flater.inflate(R.layout.brlist_main, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(oThis);
		alert_brlist = builder.create();
		alert_brlist.setView(view);
		alert_brlist.setCanceledOnTouchOutside(false);
		alert_brlist.show();
		WindowManager.LayoutParams params = alert_brlist.getWindow().getAttributes();
		params.width = screenwidth * 4 / 5;
		params.height = screenheight * 4 / 5;
		alert_brlist.getWindow().setAttributes(params);
		alert_brlist.getWindow().setContentView(R.layout.brlist_main);
		brListview = (ListView) alert_brlist.findViewById(R.id.brlist);
		bt_preview = (ImageButton) alert_brlist.findViewById(R.id.bt_preview);
		adapter = new BrListAdapter();
		brListview.setAdapter(adapter);
		brListview.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				// TODO Auto-generated method stub
				HashMap<String, String> map = (HashMap<String, String>) arg0.getItemAtPosition(arg2);
				patid = map.get("brbs");
				cardno = map.get("cardno");
				alert_brlist.dismiss();
				if (StringUtil.isEmpty(patid) || StringUtil.isEmpty(cardno))
				{
					Toast.makeText(oThis, "卡号不能为空！", Toast.LENGTH_SHORT).show();
					return;
				}
				AlertDialog.Builder builder = new AlertDialog.Builder(oThis);
				builder.setTitle("提示");
				builder.setMessage("确定要预约吗?");
				builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
				{

					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						try
						{

							Intent intent = new Intent(GhFrive.this, GhSix.class);
							intent.putExtra("strpbdate", yydate);
							intent.putExtra("strysgh", ysgh);
							intent.putExtra("pbmxid", pbmxid);
							intent.putExtra("ghf", ghf);
							intent.putExtra("ksname", ksname);
							intent.putExtra("ksid", ksid);
							intent.putExtra("ysname", ysname);
							intent.putExtra("patid", patid);
							intent.putExtra("cardno", cardno);

							startActivity(intent);
						}
						catch (Exception e)
						{
							MessageUtils.showMsgToastBottom(oThis, "保存失败！");
						}
					}
				});
				builder.setNegativeButton("取消", null);
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}
		});
		bt_preview.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				alert_brlist.dismiss();
			}
		});
	}

	private void initYyDialog()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(oThis);
		builder.setTitle("提示");
		builder.setMessage("确定要预约吗?");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
		{

			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				try
				{

					Intent intent = new Intent(GhFrive.this, GhSix.class);
					intent.putExtra("strpbdate", yydate);
					intent.putExtra("strysgh", ysgh);
					intent.putExtra("pbmxid", pbmxid);
					intent.putExtra("ghf", ghf);
					intent.putExtra("ksname", ksname);
					intent.putExtra("ksid", ksid);
					intent.putExtra("ysname", ysname);
					intent.putExtra("patid", patid);
					intent.putExtra("cardno", cardno);

					startActivity(intent);
				}
				catch (Exception e)
				{
					MessageUtils.showMsgToastBottom(oThis, "保存失败！");
				}
			}
		});
		builder.setNegativeButton("取消", null);
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}

}
